﻿using System.Linq;
using INHollandair.Data;

namespace INHollandair.Core.Repositories
{
    public class OrderRepository
    {
        //Database object
        private readonly PresentatieDBDataContext _context = new PresentatieDBDataContext();

        public IQueryable<Models.Order> OrderRepo
        {
            get
            {
                return _context.Orders.Select(x => new Models.Order
                {
                    ID = x.ID,
                    UserID = x.UserID,
                    ProductID = x.ProductID,
                    OrderURL = x.OrderURL,
                    DateOrdered = x.DateOrdered,
                    confirmed = x.confirmed
                });
            }
        }

        public IQueryable<Models.OrderHistory> OrderHistoryRepo
        {
            get
            {
                return
                    from o in _context.Orders
                    join p in _context.Products
                            on o.ProductID
                            equals p.Id
                    select new Models.OrderHistory
                    {
                        ID = o.ID,
                        UserID = o.UserID,
                        ProductName = p.Name,
                        ProductPrice = p.Price,
                        OrderUrl = o.OrderURL,
                        confirmed = o.confirmed,
                        DateOrdered = o.DateOrdered
                    };
            }
        }

        public void InsertOrder(Models.Order order)
        {
            Order orderToInsert = new Order
            {
                ID = order.ID,
                UserID = order.UserID,
                ProductID = order.ProductID,
                OrderURL = order.OrderURL,
                DateOrdered = order.DateOrdered,
                confirmed = order.confirmed
            };

            _context.Orders.InsertOnSubmit(orderToInsert);
            _context.SubmitChanges();
        }
        public void UpdateOrder(Models.Order order)
        {
            Order orderToUpdate = _context.Orders.First(x => x.ID.Equals(order.ID));
            orderToUpdate.UserID = order.UserID;
            orderToUpdate.ProductID = order.ProductID;
            orderToUpdate.OrderURL = order.OrderURL;
            orderToUpdate.DateOrdered = order.DateOrdered;
            orderToUpdate.confirmed = order.confirmed;

            _context.SubmitChanges();
        }
        public void RemoveOrder(Models.Order order)
        {
            Order orderToRemove = _context.Orders.First(x => x.ID.Equals(order.ID));
            _context.Orders.DeleteOnSubmit(orderToRemove);
            _context.SubmitChanges();
        }
    }
}
